﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Milan.Diagnostics
{
	/// <summary>
	/// The progress class should be enclosed in a using, in order to destroy it
	/// </summary>
	public class Progress : IDisposable	
	{
		public Progress(string nameOfGroup = null, int totalSteps = -1)
		{
			m_stack.Push(this);
			m_nameOfGroup = nameOfGroup;
			string startLog = ">>>> Start " + nameOfGroup;
			if (totalSteps >= 0)
				startLog += " with " + totalSteps.ToString() + " steps";
			log.Persistent(startLog);
			++m_level;
			m_currentStep = 0;
			TotalSteps = totalSteps;
		}
		public int TotalSteps	{ get; set;	}
		private void InternalTick(int steps = 1)
		{
			m_currentStep += steps;
			log.DisplayLine((new String('\t', m_level)) + " " + m_nameOfGroup + ((m_currentStep*100)/TotalSteps)
				+ "% " + m_currentStep.ToString() + " of " + TotalSteps.ToString());
		}
		public static void Tick(int steps = 1)
		{
			m_stack.Peek().InternalTick(steps);
		}
		public void Dispose()
		{
			if (m_nameOfGroup != null)
				log.Persistent("<<<< End " + m_nameOfGroup);
			--m_level;
			m_stack.Pop();
		}
		private static int m_level = 0;
		private static Stack<Progress> m_stack = new Stack<Progress>();
		private string m_nameOfGroup;
		private int m_currentStep;
	}
}
